package com.smsc.headend.task.engine.handler.impl.dcuparam;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.HexUtil;
import com.smsc.headend.common.enums.errorcode.TaskHandlerErrorCode;
import com.smsc.headend.module.protocol.DeviceData;
import com.smsc.headend.module.protocol.cosem.bo.CosemData;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.task.engine.exception.UDISTaskHandlerException;
import com.smsc.headend.task.engine.handler.TaskHandler;
import com.smsc.headend.task.engine.service.CosemXmlService;
import com.smsc.headend.task.engine.service.FeignAssetManagementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author xiaosc
 * @date 2021/05/10 20:23
 */
@Slf4j
public class PlcOnlineListHandler implements TaskHandler {

    @Autowired
    CosemXmlService cosemXmlService;
    @Autowired
    FeignAssetManagementService assetManagementService;

    @Override
    public int handle(Task task, AtomicTask atomicTask, DeviceData deviceData, String actionResult) throws UDISTaskHandlerException {
        if (!(deviceData instanceof CosemData)) {
            throw new UDISTaskHandlerException(TaskHandlerErrorCode.DEVICE_DATA_TYPE_NOT_SUPPORT.toString());
        }

        CosemData cosemData = (CosemData) deviceData;
        List<String> list = CollUtil.newArrayList();
        if(CollUtil.isNotEmpty(cosemData.getChild())) {
            list = cosemData.getChild().stream().map(item -> {
                Object data = cosemXmlService.getData(item.getChild().get(0).getType(), item.getChild().get(0).getValue());
                return HexUtil.decodeHexStr(Convert.toStr(data)).trim();
            }).collect(Collectors.toList());
        }
        assetManagementService.handlePlcMetersStatus(task.getComId(), list, null);

        return 1;
    }

    @Override
    public int handleFailure(Task task, AtomicTask atomicTask, String message) {
        log.info("error {}, ", message);
        return -1;
    }
}
